import type { AudDialogShowParams } from '@/pages/components/Aud/AudDialog';
import { CheckBox, DropDownBox, Form, LoadIndicator, NumberBox, ScrollView, SelectBox, TextBox, } from 'devextreme-react';
import Popup from 'devextreme-react/popup';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
import { useState } from 'react';
import { intl } from '@/utils';
import { useModel } from 'umi';
import { CpasIcon, DevPopup } from '~/public/cpas-ui';
import ReportPopup from "~/public/cpas-business/components-bs/ReportPopup";
import { Addsubject, getAccountInfo, getPresetTopSubject, getSubjectType } from './service';
import "./index.less"
import DataGrid, { Column, Paging } from 'devextreme-react/data-grid';
import { Progress } from 'antd';


const FirstLevelSubjectPopup = React.forwardRef((props: any, ref: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname, zcbfid } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;
    const { AccountDataID } = props;

    const diaParams = useRef<AudDialogShowParams & any>();
    const DelteRef = useRef<any>();
    const DataGridRef = useRef<any>();
    const statementProjectRef = useRef<any>();
    const [visible, setVisible] = useState<boolean>(false);
    const [checkBoxState, setCheckBoxState] = useState<boolean>(true);
    const [accountYearData, setAccountYearData] = useState<any[]>([]);
    const [selDefaultValue, setSelDefaultValue] = useState<any>('');
    const [accountYear, setAccountYear] = useState<string>('');
    const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "left", };
    const Titlestyle: React.CSSProperties = { marginRight: "8px" }
    // const [timeData, setTimeData] = useState<string>('');
    const [firstLevelSubjectData, setFirstLevelSubjectData] = useState<any[]>([]);
    const [selectedRightData, setSelectedRightData] = useState<any[]>([]);
    const [subjectLxData, setSubjectLxData] = useState<any[]>([]);
    const [openVisible111111, setOpenVisible111111] = useState<boolean>(false);
    // const [reportPopupVisible, setReportPopupVisible] = useState<boolean>(false);
    const [progress, setProgress] = useState(0);

    const [isProgressVisible, setIsProgressVisible] = useState<boolean>(false);

    const [titlePupopParams, setTitlePupopParams] = useState<any>(
        {
            width: 550,
            height: 220,
            contentText: ['本次新增使用的编号，禁止为空 ！']
        });

    // const changeTimes = () => {
    //     setTimeData(`${new Date().getTime()}`);
    // }
    const getFetchData = async () => {
        // const auditAdjustId: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
        // const tempYear = JSON.parse(auditAdjustId)?.tabledataId ?? sjnd;
        let findTemp = -2;
        const res: any = await getAccountInfo({ dbname });
        if (res.success) {
            findTemp = res.data.findIndex((item: any) => {
                return AccountDataID === item.Data_ID;
            });
            // debugger;
            const tempIndex = findTemp >= 0 ? findTemp : 0;
            const DataId = res.data[tempIndex]?.Data_ID;
            const displayNames = res.data[tempIndex]?.displayName;
            res.data.forEach((item: any, index: any) => {
                item.index = index
                return item
            });
            setAccountYearData(res.data);
            setAccountYear(DataId);
            setSelDefaultValue(displayNames);
            // changeTimes();
        }
    }



    const getListData = async (dataStr: any) => {
        setOpenVisible111111(true);
        const resLx: any = await getSubjectType({
            dbname,
            Data_ID: dataStr,
        });
        if (resLx.success) {
            const lx = resLx.data.map((item: { type: string }) => item.type)
            setSubjectLxData(lx);
        } else {
            setSubjectLxData([]);
        }
        const res: any = await getPresetTopSubject({
            dbname,
            Data_ID: dataStr,
            zcbfID: zcbfid
        });
        if (res.success) {
            setFirstLevelSubjectData(res.data);
            await DataGridRef.current.instance.selectAll();
            setTimeout(() => {
                const dataGridRefScroll =
                    DataGridRef?.current?.instance?.getScrollable();
                if (dataGridRefScroll) {
                    dataGridRefScroll.scrollTo({ left: 0, top: 0 });
                }
                setOpenVisible111111(false);
            }, 500);
        }
    }
    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: (params: any) => {
            setCheckBoxState(true);
            diaParams.current = params;
            setProgress(0);
            setIsProgressVisible(false);
            getFetchData();
            setVisible(true);
            getListData(params.args.selectYear);
        },
        close: () => { setVisible(false) }
    }));


    const changeCheck = useCallback((v: boolean) => {
        setCheckBoxState(v);
    }, [checkBoxState]);




    // 获取列表的点击项
    // 后期获取list的数据 获取到给tabs进行处理
    const onSelectionChangeds = useCallback((e: any) => {
        getListData(e.selectedItem.Data_ID);
        setAccountYear(e.selectedItem.Data_ID);
        setSelDefaultValue(e.selectedItem.displayName);
    }, []);


    const SavedData = (e: any) => {
        if (e.changes.length) {
            const { data } = e.changes[0];
            // changetempData(data);
            console.log(data, e.changes, '@@@');
            setFirstLevelSubjectData((old: any) => {
                const newData = [...old];
                newData.forEach((item: { SubjectNo: any; KMBH: string }) => {
                    if (item.KMBH === data.KMBH) {
                        item.SubjectNo = data.SubjectNo;
                    }
                });
                return newData;
            })
        }
    }


    const bbbbb = async (newData: any[]) => {
        // const yearData = newData.data.map((item: any) => item.Data_ID);
        setOpenVisible111111(true);
        const tempA: any = [];
        for (let index = 0; index < newData.length; index++) {
            const element = newData[index];
            if (element) {
                const res = await Addsubject(element);
                if (res.ok && res.data > 0) {
                    tempA.push(Promise.resolve('ok'));
                } else {
                    tempA.push(Promise.resolve(`【(${element.Data_ID})${element.YSKMBH}-${element.KMMC}】${res.data}`));
                };
                const newProgress = Math.floor(((index + 1) / newData.length) * 100);
                setProgress(newProgress);
            }
        }


        Promise.allSettled(tempA).then(results => {
            console.log(tempA, results, '@@@');
            const falseData = results.filter((item1: any) => item1.value !== 'ok').map((item: any) => item.value);
            if (falseData.length) {
                setTitlePupopParams({
                    width: 700,
                    height: 500,
                    contentText: falseData
                });
                DelteRef.current.show({
                    title: "失败原因",
                    okCallback: () => {
                        setProgress(0);
                        setIsProgressVisible(false);
                    },
                    onCancel: () => {
                        setProgress(0);
                        setIsProgressVisible(false);
                    },
                });
            } else {
                setTitlePupopParams({
                    width: 550,
                    height: 220,
                    contentText: ['增加一级科目成功！']
                })
                DelteRef.current.show({
                    title: "提示",
                    okCallback: () => {
                        setProgress(0);
                        setIsProgressVisible(false);
                    },
                    onCancel: () => {
                        setProgress(0);
                        setIsProgressVisible(false);
                    },
                });
            }
            setOpenVisible111111(false);
            getListData(accountYear);
            diaParams.current?.okCallback();
        }).catch(error => {
            // 处理错误
            console.error("An error occurred:", error);
        });
    }



    const okBtn = () => {
        DataGridRef.current.instance.saveEditData().then(async () => {
            const res = DataGridRef.current.instance.getSelectedRowsData();
            if (res.length === 0) {
                setTitlePupopParams({
                    width: 550,
                    height: 220,
                    contentText: ['请选择需要添加的科目！']
                })
                DelteRef.current.show({
                    title: "提示",
                    okCallback: () => {
                    }
                });
                return;
            }
            const reK = res.filter((item: any) => !item.SubjectNo || !item.SubjectType || !item.SubjectDirection);
            if (reK.length) {
                setTitlePupopParams({
                    width: 550,
                    height: 220,
                    contentText: ['新增一级科目的科目方向、科目类型、本次新增使用的编号，禁止为空 ！']
                })
                DelteRef.current.show({
                    title: "提示",
                    okCallback: () => {
                    }
                });
                return;
            }
            setProgress(0);
            setIsProgressVisible(true);
            // console.log(firstLevelSubjectData, res, '@@@');
            let tempData: any = [];
            res.forEach((items: any) => {
                const tempObj = {
                    dbname,
                    editUser: username,
                    KMFX: items.SubjectDirection,
                    KMLX: items.SubjectType,
                    itemNames: items.ItemName,
                    YSKMBH: `${items.SubjectNo}`,
                    YSKMMC: items.SubjectName,
                    KMBH: `${items.SubjectNo}~|`,
                    KMMC: items.SubjectName,
                    PKMBH: "",
                    JC: 1
                }
                tempData.push(tempObj);
            });
            let saveData: any = [];
            if (checkBoxState) {
                accountYearData.forEach((year: any) => {
                    let newDataArray = tempData.map((items: any) => {
                        return { ...items, Data_ID: year.Data_ID };
                    });
                    saveData = saveData.concat(newDataArray);
                });
            } else {
                tempData.forEach((items: any) => {
                    let newDataObject = { ...items, Data_ID: accountYear };
                    saveData.push(newDataObject);
                });
            }
            await bbbbb(saveData);
            return;
        });
    };
    const onSelectionChangedRight = useCallback(({ selectedRowKeys }: any) => {
        setSelectedRightData(selectedRowKeys);
    }, []);

    const changeItemName = (rowData: any, isClear: boolean, itemData: any = {}) => {
        setFirstLevelSubjectData((old: any) => {
            const newData = [...old];
            if (isClear) {
                newData.forEach((item: { ItemName: any; ItemNo: any; KMBH: string }) => {
                    if (item.KMBH === rowData.KMBH) {
                        item.ItemName = null;
                        item.ItemNo = null;
                    }
                });
            } else {
                newData.forEach((item: { ItemName: any; ItemNo: any; KMBH: string }) => {
                    if (item.KMBH === rowData.KMBH) {
                        item.ItemName = itemData.ItemName;
                        item.ItemNo = itemData.ItemNo;
                    }
                });
            }

            return newData;
        })
    }


    const cancelFun = () => {
        if (!openVisible111111) {
            setVisible(false);
        }
    }

    return (
        <>
            <Popup
                ref={ref}
                visible={visible}
                title={diaParams.current?.args?.title}
                wrapperAttr={{
                  class: "fix-popup-title-width"
                }}
                width={1000}
                height={700}
                onHiding={() => cancelFun()}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => cancelFun()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => okBtn()
                        },
                    },
                ]}
                // dragOutsideBoundary={true}
                resizeEnabled={true}
            >
                {openVisible111111 && <div style={{
                    position: 'absolute',
                    width: '960px',
                    height: '625px',
                    display: 'flex', alignItems: "center", justifyContent: "center",
                    opacity: 0.5, zIndex: "99999", background: "#ddd"
                }}>
                    <LoadIndicator id="medium-indicator" height={50} width={50} />
                </div>}

                <div style={{ width: "100%", height: "100%" }} className='subjectsBox' >
                    <div style={{ marginBottom: "15px" }}>
                        {useMemo(() => {
                            if (selDefaultValue) {
                                return <div style={Divstyle}>
                                    <div style={Titlestyle}>{intl('report.subject.account', '账套:')}</div>
                                    <SelectBox
                                        width={200}
                                        dataSource={accountYearData}
                                        displayExpr='displayName'
                                        valueExpr='displayName'
                                        value={selDefaultValue}
                                        onSelectionChanged={onSelectionChangeds}
                                        dropDownOptions={{
                                            width: '350px'
                                        }} />
                                </div>
                            }
                            return <div style={{ height: "32px" }}>loading...</div>
                        }, [selDefaultValue])}
                    </div>
                    <DataGrid
                        // width={650}
                        ref={DataGridRef}
                        height={515}
                        className='PaperDevSortableGrid devHeadersCenter'
                        dataSource={firstLevelSubjectData}
                        keyExpr="KMBH"
                        // focusedRowEnabled={true}
                        hoverStateEnabled={true}
                        showBorders={true}
                        showColumnLines={false}
                        // 显示行的线
                        showRowLines={true}
                        allowColumnResizing={false}
                        onSaved={SavedData}
                        selectedRowKeys={selectedRightData}
                        selection={{
                            mode: 'multiple',
                            selectAllMode: 'allPages',
                            showCheckBoxesMode: 'always',
                        }}
                        onSelectionChanged={onSelectionChangedRight}
                        editing={{
                            mode: "cell",
                            startEditAction: 'click',
                            allowUpdating: true,
                        }}
                    >
                        <Paging enabled={false} />
                        <Column caption='推荐科目编号' allowEditing={false}
                            width={120} dataField="KMBH" alignment='left' />
                        <Column caption='科目名称' allowEditing={false}
                            width={200} dataField="SubjectName" alignment='left' />
                        <Column caption='科目方向'
                            width={90} dataField="SubjectDirection" alignment='left'
                            lookup={{
                                dataSource: ['借', '贷'],
                                searchEnabled: true,
                            }} />
                        <Column caption='科目类型'
                            width={90} dataField="SubjectType" alignment='left'
                            lookup={{
                                dataSource: subjectLxData,
                                searchEnabled: true,
                            }}
                        />
                        <Column caption='本次新增使用的编号' dataField="SubjectNo" dataType="number" alignment='left' />
                        <Column caption='对应的报表项目'
                            width={300}
                            dataField="ItemName" alignment='left'
                            allowEditing={false}
                            cellRender={(cell: any) => {
                                let tempItemName = '';
                                if (cell.data.ItemName) {
                                    tempItemName = cell.data.ItemName;
                                }
                                return <>
                                    <div style={{ display: "flex", alignItems: 'center', justifyContent: "space-between", paddingRight: "16px" }}>
                                        <div style={{ width: '249px', padding: "0 1px", overflow: "hidden", textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                                            title={tempItemName}>
                                            {tempItemName}
                                        </div>
                                        <div style={{ width: '40px' }}>
                                            <CpasIcon type='icon-ellipsis' onClick={() => {
                                                // changeGetFiltration(cell.data);
                                                statementProjectRef.current.show({
                                                    title: "选择报表项目",
                                                    dbname: dbname,
                                                    Data_ID: accountYear,
                                                    ownerReport: '',
                                                    selectMode: '1',
                                                    // 选择 模式 0：单选 1：多选连机选择
                                                    okCallback: (r: any) => {
                                                        // console.log(r, '@@@');
                                                        const res = r.map((item: any) => {
                                                            return item.itemName
                                                        }).join(',');
                                                        const resNo = r.map((item: any) => {
                                                            return item.code
                                                        }).join(',');
                                                        changeItemName(cell.data, false, { ItemName: res, ItemNo: resNo });
                                                        // setSelectedYears(res);

                                                    },
                                                });


                                            }} />
                                            <span style={{ marginLeft: '8px' }} >
                                                <CpasIcon type="icon-close1" onClick={() => {
                                                    console.log('清空11', '@@@');
                                                    changeItemName(cell.data, true);
                                                }} />
                                            </span>

                                        </div>

                                    </div>
                                </>
                            }}
                        />
                    </DataGrid>
                    <div className='isAddMoreYear'>
                        <div style={{ marginRight: '8px', display: 'flex', alignItems: 'center' }}>
                            <span style={{ marginLeft: '8px', marginRight: '10px', whiteSpace: 'nowrap' }}>是否增加多年度:</span><CheckBox value={checkBoxState}
                                onValueChange={(e: any) => {
                                    changeCheck(e);
                                }} />
                        </div>
                        {isProgressVisible && <Progress
                            strokeColor={{
                                '0%': '#108ee9',
                                '100%': '#87d068',
                            }}
                            percent={progress}
                        />}
                    </div>

                </div>
            </Popup>
            <DevPopup.Default ref={DelteRef} width={titlePupopParams.width} height={titlePupopParams.height}  wrapperAttr={{
                class: "fix-popup-title-width"
              }}>
                {() => {
                    return <ScrollView width='100%' height={`${titlePupopParams.height - 130}px`}>
                        <div>
                            {titlePupopParams.contentText.map((item: any) => {
                                return <div>{item}</div>
                            })}
                        </div>

                    </ScrollView>
                }}
            </DevPopup.Default>
            <ReportPopup 
              ref={statementProjectRef}  
              wrapperAttr={{
                class: "fix-popup-title-width"
              }}
            />
        </>
    );
});
export default FirstLevelSubjectPopup;